function r = kclus(Kfile,Lfile)
%
% load kernel matrix K from space delimited file Kfile
% calculate distance matrix (as U-vector. U as in LU factorisation)
% cluster data (and display as dendrogram with labels from Lfile)
% return cluster matrix
%

%path = 'C:\sites\price\phd\mypapers\ijcai05\kernels\';
path = 'Z:\simonp\Documents\svn_kernels';

K = csvread([path,Kfile]);
Du = pdist(K);
C = linkage(Du);
L = importdata([path,Lfile]);
%figure;
dendrogram(C,0,'labels',L,'orientation','left','colorthreshold','default');

HC = cluster(C,'criterion','distance','cutoff',3);
%HC = cluster(C,'criterion','inconsistent','cutoff',3);

% create a logical matrix H indicating pairwise co-membership of same cluster
noofclusters = max(HC);
H = zeros(size(K));	%which could be  H = zeros(length(HC),length(HC));
for c = 1:noofclusters
	cix = find(HC == c);
	clen = length(cix);
	for j= 1:clen
		for k = 1:clen
			H(cix(j),cix(k)) = 1;
		end
	end
end


Tfile = '\out\cora-ref\disttruth.csv';
TC = csvread([path,Tfile]);

% create a logical matrix T indicating pairwise co-membership of same cluster
noofclusters = max(TC);
T = zeros(size(K));
for c = 1:noofclusters
	cix = find(TC == c);
	clen = length(cix);
	for j= 1:clen
		for k = 1:clen
			T(cix(j),cix(k)) = 1;
		end
	end
end

tp = (sum(sum(T&H))-length(T))/2;
fp = sum(sum(~T&H))/2;
fn = sum(sum(T&~H))/2;
tn = sum(sum(~(T|H)))/2;   %i.e. ~T&~H

precision = tp/(tp + fp);
recall = tp/(tp + fn);
alpha = 1/3;
f1 = (1+alpha)*(precision*recall)/(alpha*precision + recall);

%ALSO....
%look at idea of precision and recall of ranks: one rank for each row in K and then take average P, R values

% output clusters [only to console at present!]
%noofclusters = max(HC);
%for i = 1:noofclusters
%	ix = find(HC == i);
%	L(ix)
%end

r = T;
